<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>Redis高并发缓存架构实战 |  Sword Heart</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="Sword Heart" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-03-00-08-Redis高并发缓存架构实战"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Redis高并发缓存架构实战
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/" class="article-date">
  <time datetime="2022-06-03T13:37:44.000Z" itemprop="datePublished">2022-06-03</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a> / <a class="article-category-link" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/%E5%88%86%E5%B8%83%E5%BC%8F/">分布式</a> / <a class="article-category-link" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/%E5%88%86%E5%B8%83%E5%BC%8F/redis/">redis</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">3.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">14 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p id="hitokoto">正在加载一言...</p>

<h2 id="一、Redis高并发缓存架构实战"><a href="#一、Redis高并发缓存架构实战" class="headerlink" title="一、Redis高并发缓存架构实战"></a>一、Redis高并发缓存架构实战</h2><h3 id="1、Redis集群架构下的分布式锁存在什么问题？"><a href="#1、Redis集群架构下的分布式锁存在什么问题？" class="headerlink" title="1、Redis集群架构下的分布式锁存在什么问题？"></a>1、Redis集群架构下的分布式锁存在什么问题？</h3><ul>
<li><p>主从节点切换可能会丢失redis锁的key</p>
<blockquote>
<p>比如：有一个主从redis（RedisA作为master，RedisB作为slave）线程一写RedisA成功，返回给客户端（RedisB还没来得及同步key），之后RedisA挂掉了，RedisB切换为主节点；此时线程二请求加锁，可以加锁成功</p>
<p>ZooKeeper可以解决节点切换导致key丢失的问题，但是性能不如redis</p>
</blockquote>
</li>
<li><p>RedLock能解决上述节点切换丢失redis 分布式锁key的问题吗？</p>
<blockquote>
<p>红锁原理：使用红锁，先要配置多个Redis节点（非集群，彼此之间没有关联，对等的单节点）。加锁的时候对多个Redis节点加锁，多个节点的返回结果要大于半数以上才算加锁成功（比如有3个节点，至少有两个反馈加锁成功，才认为加锁成功，所以第一个问题就来了，多个节点挂掉后，后续加锁操作可能无法进行）。<strong>红锁不推荐使用。</strong></p>
<p><strong>红锁的使用：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">String lockKey = <span class="string">&quot;product_001&quot;</span>;</span><br><span class="line">        <span class="comment">//这里需要自己实例化不同redis实例的redisson客户端连接，这里只是伪代码用一个redisson客户端简化了</span></span><br><span class="line">        RLock lock1 = redisson1.getLock(lockKey);</span><br><span class="line">        RLock lock2 = redisson2.getLock(lockKey);</span><br><span class="line">        RLock lock3 = redisson3.getLock(lockKey);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 根据多个 RLock 对象构建 RedissonRedLock （最核心的差别就在这里）</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        RedissonRedLock redLock = <span class="keyword">new</span> RedissonRedLock(lock1, lock2, lock3);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * waitTimeout 尝试获取锁的最大等待时间，超过这个值，则认为获取锁失败</span></span><br><span class="line"><span class="comment">             * leaseTime   锁的持有时间,超过这个时间锁会自动失效（值应设置为大于业务处理的时间，确保在锁有效期内业务能处理完）</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">boolean</span> res = redLock.tryLock(<span class="number">10</span>, <span class="number">30</span>, TimeUnit.SECONDS);</span><br><span class="line">            <span class="keyword">if</span> (res) &#123;</span><br><span class="line">                <span class="comment">//成功获得锁，在这里处理业务</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;lock fail&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//无论如何, 最后都要解锁</span></span><br><span class="line">            redLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;end&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>红锁存在的问题：</p>
<p>1&gt;  如果redis每个节点为了保证可用性一般会加从节点；比如有三组Redis（【redis1主、redis2从】、【redis3主、redis4从】、【redis5主、redis6从】）。线程thread1加锁redis1节点成功，加锁thread3节点成功，此时从节点redis4数据还没有同步，然后redis3节点挂了；这个时候有thread2加锁，redis1节点加锁失败（因为被thread1加锁占用）、redis4加锁成功（redis3挂了，redis4就成了主节点，redis4没有同步之前redis3的数据，故可以加锁成功），redis5加锁成功（thread1还没有对thread5加锁）</p>
<p>可能的解决方法：</p>
<p>①不加从节点：有问题，当多个主节点挂了，因为加锁成功半数机制存在，可能导致后续所有的锁都无法加锁成功</p>
<p>②多搞几个节点：性能问题，节点越多，性能越差。用redis本来就是追求高性能，这样适得其反，还不如用zk。</p>
<p>2&gt; 持久化问题：redis一般会用aof持久化。一般是一秒执行一次持久化。那么究存在问题，这一秒之内的数据可能会丢失，可能导致锁的key丢失，从而造成多个线程对同一个锁key加锁成功，这样就有问题。</p>
</blockquote>
</li>
</ul>
<h3 id="2、大促场景下分布式锁性能提升"><a href="#2、大促场景下分布式锁性能提升" class="headerlink" title="2、大促场景下分布式锁性能提升"></a>2、大促场景下分布式锁性能提升</h3><ul>
<li><p>锁的粒度：越小越好，没有必要加锁的代码并行执行</p>
</li>
<li><p>分段锁的思想：</p>
<blockquote>
<p>举例一个秒杀减库存场景：</p>
<p>redis中的key：product_101_stock     value ：500（初始库存）</p>
<p>分段锁的思想是：把这个500个库存分为多个key存储，比如五个</p>
<p>{key:product_101_stock_1     value ：100}</p>
<p>{key:product_101_stock_2     value ：100}</p>
<p>{key:product_101_stock_3     value ：100}</p>
<p>{key:product_101_stock_4     value ：100}</p>
<p>{key:product_101_stock_5     value ：100}</p>
<p>由原来的一次性用一个key锁500个库存，改为用5个key分别锁100个库存</p>
<p>减库存的时候多个线程就可以减不同key的库存，（每个线程来的时候可以随机/轮询选择某个key，当一个key库存减完，就设置一个标记，下次线程就不选这个key了）。1.7的ConcurrentHashMap中就用到了分段锁的思想。</p>
</blockquote>
</li>
</ul>
<h3 id="3、大厂的缓存架构实现"><a href="#3、大厂的缓存架构实现" class="headerlink" title="3、大厂的缓存架构实现"></a>3、大厂的缓存架构实现</h3><p><img src="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/image-20220603222145251.png" alt="image-20220603222145251"></p>
<ul>
<li><p>大规模商品缓存数据冷热分离</p>
<p><img src="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/image-20220603224606359.png" alt="image-20220603224606359"></p>
</li>
<li><p>缓存击穿（缓存失效）</p>
<blockquote>
<p>定义：由于大批量缓存在同一时间失效可能导致大量请求同时穿透缓存直达数据库，可能会造成数据库瞬间压力过大甚至挂掉，对于这种情况我们在批量增加缓存时最好<strong>将这一批数据的缓存过期时间设置为一个时间段内的不同时间。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">## 过期时间设置为随机数</span><br><span class="line"><span class="function"><span class="keyword">private</span> Integer <span class="title">genProductCacheTimeout</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//加随机超时机制解决缓存批量失效(击穿)问题</span></span><br><span class="line">        <span class="keyword">return</span> PRODUCT_CACHE_TIMEOUT + <span class="keyword">new</span> Random().nextInt(<span class="number">5</span>) * <span class="number">60</span> * <span class="number">60</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>缓存穿透</p>
<blockquote>
<p>缓存穿透是指查询一个根本不存在的数据， 缓存层和存储层都不会命中， 通常出于容错的考虑， 如果从存储层查不到数据则不写入缓存层。</p>
<p>缓存穿透将导致不存在的数据每次请求都要到存储层去查询， 失去了缓存保护后端存储的意义。</p>
<p>造成缓存穿透的基本原因有两个：</p>
<p>第一， 自身业务代码或者数据出现问题。</p>
<p>第二， 一些恶意攻击、 爬虫等造成大量空命中。 </p>
<p>缓存穿透问题解决方案：</p>
<ul>
<li><p>1、缓存空对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">String <span class="title">get</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 从缓存中获取数据</span></span><br><span class="line">    String cacheValue = cache.get(key);</span><br><span class="line">    <span class="comment">// 缓存为空</span></span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isBlank(cacheValue)) &#123;</span><br><span class="line">        <span class="comment">// 从存储中获取</span></span><br><span class="line">        String storageValue = storage.get(key);</span><br><span class="line">        cache.set(key, storageValue);</span><br><span class="line">        <span class="comment">// 如果存储数据为空， 需要设置一个过期时间(300秒)</span></span><br><span class="line">        <span class="keyword">if</span> (storageValue == <span class="keyword">null</span>) &#123;</span><br><span class="line">            cache.expire(key, <span class="number">60</span> * <span class="number">5</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> storageValue;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 缓存非空</span></span><br><span class="line">        <span class="keyword">return</span> cacheValue;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>2、布隆过滤器</p>
<p>对于恶意攻击，向服务器请求大量不存在的数据造成的缓存穿透，还可以用布隆过滤器先做一次过滤，对于不存在的数据布隆过滤器一般都能够过滤掉，不让请求再往后端发送。当布隆过滤器说<strong>某个值存在时，这个值可能不存在；当它说不存在时，那就肯定不存在。</strong></p>
<p><img src="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/image-20220603230112939.png" alt="image-20220603230112939"></p>
<p>布隆过滤器就是<strong>一个大型的位数组和几个不一样的无偏 hash 函数</strong>。所谓无偏就是能够把元素的 hash 值算得比较均匀。</p>
<p>向布隆过滤器中添加 key 时，会使用多个 hash 函数对 key 进行 hash 算得一个整数索引值然后对位数组长度进行取模运算得到一个位置，每个 hash 函数都会算得一个不同的位置。再把位数组的这几个位置都置为 1 就完成了 add 操作。</p>
<p>向布隆过滤器询问 key 是否存在时，跟 add 一样，也会把 hash 的几个位置都算出来，看看位数组中这几个位置是否都为 1，只要有一个位为 0，那么说明布隆过滤器中这个key 不存在。如果都是 1，这并不能说明这个 key 就一定存在，只是极有可能存在，因为这些位被置为 1 可能是因为其它的 key 存在所致。如果这个位数组长度比较大，存在概率就会很大，如果这个位数组长度比较小，存在概率就会降低。</p>
<p>这种方法适用于数据命中不高、 数据相对固定、 实时性低（通常是数据集较大） 的应用场景， 代码维护较为复杂， 但是<strong>缓存空间占用很少</strong>。</p>
<p>可以用redisson实现布隆过滤器，引入依赖：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">   &lt;groupId&gt;org.redisson&lt;/groupId&gt;</span><br><span class="line">   &lt;artifactId&gt;redisson&lt;/artifactId&gt;</span><br><span class="line">   &lt;version&gt;<span class="number">3.6</span><span class="number">.5</span>&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.redisson;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.redisson.Redisson;</span><br><span class="line"><span class="keyword">import</span> org.redisson.api.RBloomFilter;</span><br><span class="line"><span class="keyword">import</span> org.redisson.api.RedissonClient;</span><br><span class="line"><span class="keyword">import</span> org.redisson.config.Config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedissonBloomFilter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Config config = <span class="keyword">new</span> Config();</span><br><span class="line">        config.useSingleServer().setAddress(<span class="string">&quot;redis://localhost:6379&quot;</span>);</span><br><span class="line">        <span class="comment">//构造Redisson</span></span><br><span class="line">        RedissonClient redisson = Redisson.create(config);</span><br><span class="line"></span><br><span class="line">        RBloomFilter&lt;String&gt; bloomFilter = redisson.getBloomFilter(<span class="string">&quot;nameList&quot;</span>);</span><br><span class="line">        <span class="comment">//初始化布隆过滤器：预计元素为100000000L,误差率为3%,根据这两个参数会计算出底层的bit数组大小</span></span><br><span class="line">        bloomFilter.tryInit(<span class="number">100000000L</span>,<span class="number">0.03</span>);</span><br><span class="line">        <span class="comment">//将zhuge插入到布隆过滤器中</span></span><br><span class="line">        bloomFilter.add(<span class="string">&quot;zhuge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断下面号码是否在布隆过滤器中</span></span><br><span class="line">        System.out.println(bloomFilter.contains(<span class="string">&quot;guojia&quot;</span>));<span class="comment">//false</span></span><br><span class="line">        System.out.println(bloomFilter.contains(<span class="string">&quot;baiqi&quot;</span>));<span class="comment">//false</span></span><br><span class="line">        System.out.println(bloomFilter.contains(<span class="string">&quot;zhuge&quot;</span>));<span class="comment">//true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：布隆过滤器不能删除数据，如果要删除得重新初始化数据。</p>
</li>
</ul>
</blockquote>
</li>
<li><p>缓存雪崩</p>
<p>缓存雪崩指的是缓存层支撑不住或宕掉后， 流量会像奔逃的野牛一样， 打向后端存储层。</p>
<p>由于缓存层承载着大量请求， 有效地保护了存储层， 但是如果缓存层由于某些原因不能提供服务(比如超大并发过来，缓存层支撑不住，或者由于缓存设计不好，类似大量请求访问bigkey，导致缓存能支撑的并发急剧下降)， 于是大量请求都会打到存储层， 存储层的调用量会暴增， 造成存储层也会级联宕机的情况。 </p>
<p>预防和解决缓存雪崩问题， 可以从以下三个方面进行着手。</p>
<p>1） 保证缓存层服务高可用性，比如使用Redis Sentinel或Redis Cluster。</p>
<p>2） 依赖隔离组件为后端限流熔断并降级。比如使用Sentinel或Hystrix限流降级组件。</p>
<p>比如服务降级，我们可以针对不同的数据采取不同的处理方式。当业务应用访问的是非核心数据（例如电商商品属性，用户信息等）时，暂时停止从缓存中查询这些数据，而是直接返回预定义的默认降级信息、空值或是错误提示信息；当业务应用访问的是核心数据（例如电商商品库存）时，仍然允许查询缓存，如果缓存缺失，也可以继续通过数据库读取。</p>
<p>3） 提前演练。 在项目上线前， 演练缓存层宕掉后， 应用以及后端的负载情况以及可能出现的问题， 在此基础上做一些预案设定。</p>
<p>4）多级缓存架构</p>
<ul>
<li><p>加一级JVM缓存【每秒可以抗百万并发】，这种方案要考虑不同服务器间的jvm缓存的一致性，可以通过mq、redis发布订阅等方式解决。</p>
</li>
<li><p>还可能出现短时间的数据不一致，使用了多级缓存，一般这种场景可以容忍。</p>
</li>
<li><p>大型互联网公司，还会有热点缓存计算系统（一种可以实现的方式：对redis的数据做aop拦截，然后将redis数据发送到计算系统中，计算系统通过大数据的实时计算系统维护热点缓存，这样web应用系统也做了解耦）【负责put热点数据，web应用系统直接get获取】，所有的web应用会跟这个系统建立联系，比如监听（web应用监听到缓存系统的数据之后，就将数据写入到自己本地缓存）。为什么不web应用自己维护本地缓存，自己put呢？因为数据会变化，可能现在是热点数据，过一会就不是热点数据了。</p>
</li>
</ul>
</li>
<li><p>突发性热点缓存重建导致系统压力暴增</p>
<ul>
<li><p>DCL双重检查锁：使用于单机，如果集群环境使用，可能重建缓存会多次</p>
</li>
<li><p>分布式锁重建缓存</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Product <span class="title">get</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">        Product product = <span class="keyword">null</span>;</span><br><span class="line">        String productCacheKey = RedisKeyPrefixConst.PRODUCT_CACHE + productId;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//从缓存里查数据</span></span><br><span class="line">        product = getProductFromCache(productCacheKey);</span><br><span class="line">        <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> product;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//加分布式锁解决热点缓存并发重建问题</span></span><br><span class="line">        RLock hotCreateCacheLock = redisson.getLock(LOCK_PRODUCT_HOT_CACHE_CREATE_PREFIX + productId);</span><br><span class="line">        hotCreateCacheLock.lock();</span><br><span class="line">        <span class="comment">// 这个优化谨慎使用，防止超时导致的大规模并发重建问题</span></span><br><span class="line">        <span class="comment">// hotCreateCacheLock.tryLock(1, TimeUnit.SECONDS);</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            product = getProductFromCache(productCacheKey);</span><br><span class="line">            <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> product;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//RLock productUpdateLock = redisson.getLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span></span><br><span class="line">            RReadWriteLock productUpdateLock = redisson.getReadWriteLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span><br><span class="line">            RLock rLock = productUpdateLock.readLock();</span><br><span class="line">            <span class="comment">//加分布式读锁解决缓存双写不一致问题</span></span><br><span class="line">            rLock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                product = productDao.get(productId);</span><br><span class="line">                <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    redisUtil.set(productCacheKey, JSON.toJSONString(product),</span><br><span class="line">                            genProductCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">//设置空缓存解决缓存穿透问题</span></span><br><span class="line">                    redisUtil.set(productCacheKey, EMPTY_CACHE, genEmptyCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                rLock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            hotCreateCacheLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> product;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>缓存和数据库双写不一致问题</p>
<p>​    原因：</p>
<p>​    </p>
<p><img src="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/image-20220604174453971.png" alt="image-20220604174453971"></p>
<p>​    <img src="/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/image-20220604174616840.png" alt="image-20220604174616840"></p>
<ul>
<li>加分布式锁</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Product <span class="title">get</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">       Product product = <span class="keyword">null</span>;</span><br><span class="line">       String productCacheKey = RedisKeyPrefixConst.PRODUCT_CACHE + productId;</span><br><span class="line">  </span><br><span class="line">       <span class="comment">//从缓存里查数据</span></span><br><span class="line">       product = getProductFromCache(productCacheKey);</span><br><span class="line">       <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="keyword">return</span> product;</span><br><span class="line">       &#125;</span><br><span class="line">  </span><br><span class="line">       <span class="comment">//加分布式锁解决热点缓存并发重建问题</span></span><br><span class="line">       RLock hotCreateCacheLock = redisson.getLock(LOCK_PRODUCT_HOT_CACHE_CREATE_PREFIX + productId);</span><br><span class="line">       hotCreateCacheLock.lock();</span><br><span class="line">       <span class="comment">// 这个优化谨慎使用，防止超时导致的大规模并发重建问题</span></span><br><span class="line">       <span class="comment">// hotCreateCacheLock.tryLock(1, TimeUnit.SECONDS);</span></span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           product = getProductFromCache(productCacheKey);</span><br><span class="line">           <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">               <span class="keyword">return</span> product;</span><br><span class="line">           &#125;</span><br><span class="line">  </span><br><span class="line">           RLock productUpdateLock = redisson.getLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span><br><span class="line">           <span class="comment">// RReadWriteLock productUpdateLock = redisson.getReadWriteLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span></span><br><span class="line">           <span class="comment">// RLock rLock = productUpdateLock.readLock();</span></span><br><span class="line">           <span class="comment">//加分布式读锁解决缓存双写不一致问题</span></span><br><span class="line">           productUpdateLock.lock();</span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">               product = productDao.get(productId);</span><br><span class="line">               <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">                   redisUtil.set(productCacheKey, JSON.toJSONString(product),</span><br><span class="line">                           genProductCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">               &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                   <span class="comment">//设置空缓存解决缓存穿透问题</span></span><br><span class="line">                   redisUtil.set(productCacheKey, EMPTY_CACHE, genEmptyCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">               productUpdateLock.unlock();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           hotCreateCacheLock.unlock();</span><br><span class="line">       &#125;</span><br><span class="line">  </span><br><span class="line">       <span class="keyword">return</span> product;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>读多写少【主要说的是数据库的读和写】的场景，使用分布式的读写锁，使用Redisson的ReadWriteLock</p>
<p>如下示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">public</span> Product <span class="title">get</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">        Product product = <span class="keyword">null</span>;</span><br><span class="line">        String productCacheKey = RedisKeyPrefixConst.PRODUCT_CACHE + productId;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//从缓存里查数据</span></span><br><span class="line">        product = getProductFromCache(productCacheKey);</span><br><span class="line">        <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> product;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//加分布式锁解决热点缓存并发重建问题</span></span><br><span class="line">        RLock hotCreateCacheLock = redisson.getLock(LOCK_PRODUCT_HOT_CACHE_CREATE_PREFIX + productId);</span><br><span class="line">        hotCreateCacheLock.lock();</span><br><span class="line">        <span class="comment">// 这个优化谨慎使用，防止超时导致的大规模并发重建问题</span></span><br><span class="line">        <span class="comment">// hotCreateCacheLock.tryLock(1, TimeUnit.SECONDS);</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            product = getProductFromCache(productCacheKey);</span><br><span class="line">            <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> product;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//RLock productUpdateLock = redisson.getLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span></span><br><span class="line">            RReadWriteLock productUpdateLock = redisson.getReadWriteLock(LOCK_PRODUCT_UPDATE_PREFIX + productId);</span><br><span class="line">            RLock rLock = productUpdateLock.readLock(); <span class="comment">// 加读锁</span></span><br><span class="line">            <span class="comment">//加分布式读锁解决缓存双写不一致问题</span></span><br><span class="line">            rLock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                product = productDao.get(productId);</span><br><span class="line">                <span class="keyword">if</span> (product != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    redisUtil.set(productCacheKey, JSON.toJSONString(product),</span><br><span class="line">                            genProductCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">//设置空缓存解决缓存穿透问题</span></span><br><span class="line">                    redisUtil.set(productCacheKey, EMPTY_CACHE, genEmptyCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                rLock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            hotCreateCacheLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> product;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">## 加写锁</span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Product <span class="title">update</span><span class="params">(Product product)</span> </span>&#123;</span><br><span class="line">        Product productResult = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">//RLock productUpdateLock = redisson.getLock(LOCK_PRODUCT_UPDATE_PREFIX + product.getId());</span></span><br><span class="line">        RReadWriteLock productUpdateLock = redisson.getReadWriteLock(LOCK_PRODUCT_UPDATE_PREFIX + product.getId());</span><br><span class="line">        RLock writeLock = productUpdateLock.writeLock(); <span class="comment">// 加写锁</span></span><br><span class="line">        <span class="comment">//加分布式写锁解决缓存双写不一致问题</span></span><br><span class="line">        writeLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            productResult = productDao.update(product);</span><br><span class="line">            redisUtil.set(RedisKeyPrefixConst.PRODUCT_CACHE + productResult.getId(), JSON.toJSONString(productResult),</span><br><span class="line">                    genProductCacheTimeout(), TimeUnit.SECONDS);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            writeLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> productResult;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>缓存重建 加的分布式锁优化====&gt;加个阻塞时间，适用于明确知道执行时间的，否则不要轻易使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">##上述讲到了重建缓存加了分布式锁，代码如下</span><br><span class="line"><span class="comment">//加分布式锁解决热点缓存并发重建问题</span></span><br><span class="line">RLock hotCreateCacheLock = redisson.getLock(LOCK_PRODUCT_HOT_CACHE_CREATE_PREFIX + productId);</span><br><span class="line">hotCreateCacheLock.lock();</span><br><span class="line"><span class="comment">// 这个优化谨慎使用，防止超时导致的大规模并发重建问题</span></span><br><span class="line"><span class="comment">// hotCreateCacheLock.tryLock(1, TimeUnit.SECONDS);</span></span><br><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">    <span class="comment">// 业务逻辑</span></span><br><span class="line">&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">    hotCreateCacheLock.unlock();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://haze66.gitee.io/2022/06/03/03-00-08-Redis%E9%AB%98%E5%B9%B6%E5%8F%91%E7%BC%93%E5%AD%98%E6%9E%B6%E6%9E%84%E5%AE%9E%E6%88%98/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/" rel="tag">redis</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/06/04/03-00-09-Redis%E7%BC%93%E5%AD%98%E8%AE%BE%E8%AE%A1%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Redis缓存设计与性能优化
          
        </div>
      </a>
    
    
      <a href="/2022/06/02/10-00-01-%E8%A7%A3%E5%86%B3maven-jar%E5%8C%85%E4%B8%8B%E8%BD%BD%E6%BA%90%E7%A0%81%E9%97%AE%E9%A2%98/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">解决maven jar包下载源码问题</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "z7pjLOiS1FEJ17pkhGOjBQm4-gzGzoHsz",
    app_key: "Ytw1ShVWHkcjtz9lybfPBsVT",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> John Doe
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Sword Heart"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%97%85%E8%A1%8C/">旅行</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%91%84%E5%BD%B1/">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2021/12/11/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/player">播放器</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/pdf">文件预览</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->
 
<script src="/js/dz.js"></script>
 
<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>

</html>